<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE 实时通信演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .message-form {
            margin: 20px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .message-form input {
            width: 70%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .message-form button {
            width: 25%;
            padding: 8px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        .message-form button:hover {
            background-color: #0056b3;
        }
        .messages {
            height: 400px;
            /*垂直方向内容溢出时显示滚动条*/
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #fafafa;
            border-radius: 4px;
        }
        .message {
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
            border-left: 4px solid #007bff;
            background-color: white;
        }
        .message.heartbeat {
            border-left-color: #28a745;
            background-color: #f8fff9;
        }
        .message.data {
            border-left-color: #ffc107;
            background-color: #fffef8;
        }
        .message.welcome {
            border-left-color: #17a2b8;
            background-color: #f8fdff;
        }
        .timestamp {
            font-size: 0.8em;
            color: #666;
            float: right;
        }
        .controls {
            margin: 20px 0;
            text-align: center;
        }
        .controls button {
            margin: 0 10px;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .connect-btn {
            background-color: #28a745;
            color: white;
        }
        .disconnect-btn {
            background-color: #dc3545;
            color: white;
        }
        .clear-btn {
            background-color: #6c757d;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 SSE 实时通信演示</h1>
        
        <div id="status" class="status disconnected">
            状态: 未连接
        </div>

        <div class="controls">
            <button id="connectBtn" class="connect-btn">连接服务器</button>
            <button id="disconnectBtn" class="disconnect-btn" disabled>断开连接</button>
            <button id="clearBtn" class="clear-btn">清空消息</button>
        </div>


        <div class="message-form">
            <input type="text" id="messageInput" placeholder="输入要发送的消息..." disabled>
            <button id="sendBtn" disabled>发送消息</button>
        </div>
        <!--       这里的是显示消息的区域 -->
        <div class="messages" id="messages">
            <div class="message">等待连接到服务器...</div>
        </div>
    </div>

    <script>
        let eventSource = null;
        let isConnected = false;

        const statusDiv = document.getElementById('status');
        const messagesDiv = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const clearBtn = document.getElementById('clearBtn');

        // 连接到SSE
        function connect() {
            if (isConnected) return;

            eventSource = new EventSource('/events');  //建立SSE连接
            
            eventSource.onopen = function(event) { //当 EventSource 连接成功打开时的回调函数
                isConnected = true;
                updateStatus('已连接', 'connected');
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                messageInput.disabled = false;
                sendBtn.disabled = false;
                addMessage('系统', '连接已建立', 'welcome');
            };

            eventSource.onmessage = function(event) {   //当接收到消息时
                try {
                    const data = JSON.parse(event.data); //接收到的消息
                    addMessage(data.type, data.message, data.type, data);  //添加消息到消息列表中去
                } catch (error) {
                    addMessage('错误', '解析消息失败: ' + event.data, 'error');
                }
            };

            eventSource.onerror = function(event) {  //连接发送错误时的回调函数
                console.error('SSE连接错误:', event);
                if (isConnected) {
                    addMessage('系统', '连接出现错误', 'error');
                }
                disconnect();
            };
        }

        // 断开连接
        function disconnect() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            isConnected = false;
            updateStatus('未连接', 'disconnected');
            connectBtn.disabled = false;  //连接按钮设置为可用状态
            disconnectBtn.disabled = true;
            messageInput.disabled = true;
            sendBtn.disabled = true;
        }

        // 更新连接状态
        function updateStatus(text, className) {
            statusDiv.textContent = `状态: ${text}`;
            statusDiv.className = `status ${className}`;
        }

        // 添加消息到显示区域
        function addMessage(sender, message, type = 'message', data = null) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;   //构建不同的类型的div，将其设置对应的class属性，方便样式的设置
            
            const timestamp = new Date().toLocaleTimeString();
            let content = `<strong>${sender}:</strong> ${message}`;
            
            if (data && data.value !== undefined) {
                content += ` (值: ${data.value.toFixed(3)})`;
            }
            
            if (data && data.activeClients !== undefined) {
                content += ` (活跃连接: ${data.activeClients})`;
            }
            
            messageDiv.innerHTML = `${content}<span class="timestamp">${timestamp}</span>`;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;

            try {
                const response = await fetch('/send-message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message })
                }); //先将message发送出去

                if (response.ok) {
                    messageInput.value = '';
                    addMessage('我', message, 'message');
                } else {
                    addMessage('错误', '发送消息失败', 'error');
                }
            } catch (error) {
                addMessage('错误', '网络错误: ' + error.message, 'error');
            }
        }

        // 清空消息
        function clearMessages() {
            messagesDiv.innerHTML = '';
        }

        // 事件监听器
        connectBtn.addEventListener('click', connect);
        disconnectBtn.addEventListener('click', disconnect);
        sendBtn.addEventListener('click', sendMessage);
        clearBtn.addEventListener('click', clearMessages);
        
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {  //这里有回车的监听事件
                sendMessage();
            }
        });

        // 页面加载时自动连接
        window.addEventListener('load', function() {
            setTimeout(connect, 1000);
        });

        // 页面卸载时断开连接
        window.addEventListener('beforeunload', function() {
            disconnect();
        });
    </script>
</body>
</html>